import { ref } from "vue";
export default function useMiddleInteractive() {
  const currentShow = ref("cd");
  const middleLStyle = ref(null);
  const middleRStyle = ref(null);
  const touch = {};
  let currentView = "cd"; //手指按下后值不会发生改变

  //手指触摸时的逻辑
  function onMiddleTouchStart(e) {
    touch.startX = e.touches[0].pageX;
    touch.startY = e.touches[0].pageY;
    touch.directionLocked = "";
  }

  //手指移动时的逻辑
  function onMiddleTouchMove(e) {
    //手指移动的值
    const deltaX = e.touches[0].pageX - touch.startX;
    const deltaY = e.touches[0].pageY - touch.startY;
    //计算x，y偏移量的值
    const absDeltaX = Math.abs(deltaX);
    const absDeltaY = Math.abs(deltaY);
    //判断方向锁控制只能x轴方向滚动
    if (!touch.directionLocked) {
      //方向锁判断
      touch.directionLocked = absDeltaX >= absDeltaY ? "h" : "v";
    }
    //如果一开始就是纵向偏移的话
    if (touch.directionLocked == "v") {
      touch.directionLocked = absDeltaX >= absDeltaY ? "h" : "v";
    }
    //从cd=>lyric时left为0,反之为-屏幕宽度
    const left = currentView === "cd" ? 0 : -window.innerWidth;
    //偏移量
    const offsetWidth = Math.min(
      0,
      Math.max(left + deltaX, -window.innerWidth)
    );
    touch.percent = Math.abs(offsetWidth / window.innerWidth); //偏移比例

    //通过偏移比例来判断滚动
    if (currentView === "cd") {
      if (touch.percent > 0.2) {
        currentShow.value = "lyric";
      } else {
        currentShow.value = "cd";
      }
    } else {
      if (touch.percent < 0.8) {
        currentShow.value = "cd";
      } else {
        currentShow.value = "lyric";
      }
    }

    //实时更改透明度、位移样式
    middleLStyle.value = {
      opacity: 1 - touch.percent,
    };

    middleRStyle.value = {
      transform: `translate3d(${offsetWidth}px, 0, 0)`,
    };
  }

  //手指松开时的逻辑
  function onMiddleTouchEnd() {
    let offsetWidth;
    let opacity;
    //判断两个极端的边界条件
    if (currentShow.value === "cd") {
      currentView = "cd";
      offsetWidth = 0;
      opacity = 1;
    } else {
      currentView = "lyric";
      offsetWidth = -window.innerWidth;
      opacity = 0;
    }

    //过渡动画300ms
    const duration = 300;
    middleLStyle.value = {
      opacity,
      transitionDuration: `${duration}ms`,
    };

    middleRStyle.value = {
      transform: `translate3d(${offsetWidth}px, 0, 0)`,
      transitionDuration: `${duration}ms`,
    };
  }
  return {
    currentShow,
    middleLStyle,
    middleRStyle,
    onMiddleTouchStart,
    onMiddleTouchMove,
    onMiddleTouchEnd,
  };
}
